package com.res.service.impl;


import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.ListJoin;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.res.entity.Student;
import com.res.entity.Subjects;
import com.res.repository.StudentRepository;
import com.res.service.StudentService;
@Service
public class StudentServiceImpl implements StudentService {

	
	@Autowired
	private StudentRepository rep;
	
	@Override
	public Page<Student> getStudentAll(Student s, Pageable pageable, Integer sid) {
		
		
				return rep.findAll(get(s, sid), pageable);
	}
    
public Specification<Student> get(Student s,Integer sid){
		
		return new Specification<Student>() {
			
			@Override
			public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				Predicate predicate=criteriaBuilder.conjunction();
				List<Expression<Boolean>> expressions = predicate.getExpressions();
				if(!StringUtils.isEmpty(s.getSname())) {
					expressions.add(criteriaBuilder.like(root.get("sname"), "%"+s.getSname()+"%"));
				}				
			
				if(sid!=null&&sid!=0) {
					expressions.add(criteriaBuilder.equal(root.get("sub").get("sid"), sid));
				}
					
				return predicate;
			}
		};
		
	}
	@Override
	public String addStudent(Student s,Integer sid) {
		try {
			s.setSub(new Subjects(sid, null));
			rep.save(s);
			return "添加成功";
		} catch (Exception e) {
			e.printStackTrace();
			return "添加失败";
		}
		
	}

	@Override
	public String updateStudent(Student s,Integer sid) {
		try {
			s.setSub(new Subjects(sid, null));
			rep.save(s);
			return "修改成功";
		} catch (Exception e) {
			e.printStackTrace();
			return "修改失败";
		}
	}

	@Override
	public String deleteStudent(Integer stuid) {
		try {
			rep.deleteById(stuid);
			return "删除成功";
		} catch (Exception e) {
			e.printStackTrace();
			return "删除失败";
		}
	}

}
